package org.xingole.leetcode.binarysearch;

import java.util.Arrays;

/**
 * <a href="https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/">
 * Problem Description
 * </a>
 * 
 * <p>
 * There is an integer array nums sorted in non-decreasing order (not necessarily with
 * distinct values).
 * 
 * <p>
 * Before being passed to your function, nums is rotated at an unknown pivot index k
 * (0 <= k < nums.length) such that the resulting arary is [nums[k], nums[k+1], ...,
 * nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed).
 */
public class SearchInRotatedSortedArrayII {
    /**
     * Given the array nums after the rotation and an integer target, return true if
     * target is in nums, or false if it is not in nums.
     * 
     * You must decrease the overall operation steps as much as possible.
     */
    public boolean search(int[] nums, int target) {
        int n = nums.length;

        if (n == 0) {
            return false;
        }

        if (n == 1) {
            return nums[0] == target;
        }

        int left = 0, right = n - 1;
        while (left <= right) {
            int mid = (left + right) / 2;

            if (nums[mid] == target) {
                return true;
            }

            if (nums[left] == nums[mid] && nums[mid] == nums[right]) {
                ++left;
                --right;
            } else if (nums[left] <= nums[mid]) {
                if (nums[left] <= target && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                if (nums[mid] < target && target <= nums[n - 1]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }

        return false;
    }
}
